import os
from datetime import datetime

from django.db.models.signals import post_delete, pre_delete

from api.utils.common.db import product_file_post_delete
from api.utils.db_functions import make_uuid, make_short_uuid

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.db.models import Count, Sum

from api.utils.enums import MediaType, FilePurpose


def file_path(instance, file):
    file_ext = file.split(".")[-1]
    filename = "%s.%s" % (make_short_uuid(), file_ext)
    now = datetime.now()
    parent_folder = "advertisement/%s/%s/%02d/%02d/" % (instance.type, now.year, now.month, now.day)

    return os.path.join(parent_folder, filename)


class AdvertiseMent(models.Model):
    file = models.FileField(help_text="文件Url", upload_to=file_path, max_length=256)
    product = models.ForeignKey(
        "Porduct",
        on_delete=models.CASCADE,
        related_name="advertisement_files",
        verbose_name=_("Group"),
    )
    type = models.CharField(
        choices=FilePurpose.to_choices(), default=FilePurpose.ADVERTISEMENT.value, max_length=32
    )

    def products_id(self):
        return self.product.product_id


# 更新时删除
post_delete.connect(product_file_post_delete, sender=AdvertiseMent)
